<?php
/**
 * Created by PhpStorm.
 * User: Guangpeng Chen
 * Date: 15-1-9
 * Time: 下午11:05
 */

if (!class_exists('go_sql')) {
    include "/var/www/html/new/conf/le.je";
    $le = new go_sql();
    $le->connect();
}
if (!function_exists('ismobile')) {
    function ismobile($tel) {
        if(!preg_match('/^(14|15|13|18|17)\d{9}$/',$tel)){
            return false;
        }
        return true;
    }
}
// 转分销分润
/**
 * @param $s  object  soap实例
 * @param $ordern string 订单号
 * @param $aid int 供应商id
 * @param $mid int 分销商id
 * @param $total_fee int 金额
 * @param $orders string 订单
 * @param $to_pft bool
 * @param int $p_type /*金额类型 0帐号资金 1支付宝 2供应商处可用资金 3供应商信用额度设置 4财付通
 * @return int|string
 */
function fenRun($s, $ordern, $aid, $mid, $total_fee, $orders, $to_pft, $p_type = 1)
{
    $aid = !$aid ? (int)$orders['mainOrder']->UUaid : $aid;
    $mid = !$mid ? (int)$orders['mainOrder']->UUmid : $mid;

    $add = 0;
    $cut = 1;
    // 非自供产品获取结算价
    if($aid!=$mid){
        $total_money = 0;
        $pid = (string)$orders['mainOrder']->UUpid;// 产品 id
        $begintime = (string)$orders['mainOrder']->UUbegintime;// 游玩时间价格
        $account = (string)$orders['mainOrder']->UUfromt;// 游玩时间价格
        $ret = $s->Dynamic_Price_And_Storage($account,$pid,$begintime,1,0,0,$aid);
        if($ret==105||$ret==1065){
            $total_money = $total_fee;
        }else{
            $obj = simplexml_load_string($ret);
            $total_money = (string)$obj->Rec->UUsprice * (int)$orders['mainOrder']->UUtnum;
            // write_logs("UUsprice".(string)$obj->Rec->UUsprice,"debug.txt");
        }
        if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
            foreach($orders['childOrder'] as $key=>$child){
                $pid = (int)$child->UUpid;// 产品 id
                $ret = $s->Dynamic_Price_And_Storage($account,$pid,$begintime,1,0,0,$aid);
                if($ret!=105 && $ret!=1065){
                    $obj = simplexml_load_string($ret);
                    $total_money += (int)$obj->Rec->UUsprice * (int)$child->UUtnum;
                }
            }
        }
    }
    if($to_pft){
        //票付通总账号加钱——2015年4月13日11:56:33林农说要添加，宝椿提供的代码
        // 2015年9月1日14:44:50——取消管理员账号加钱
//            $s->PFT_Member_Fund_Modify(1, 0, $total_fee, $add, 0,null,0, 0,$ordern);
        // 支付给了票付通，购买者账户加钱
        $s->PFT_Member_Fund_Modify($aid, 0, $total_fee, $add, 0, null, 0, $p_type, $ordern);
    }

    // 产品多级销售分润
//    $str="select aids_money from uu_order_fx_details where orderid='$ordern' limit 1";
//    $GLOBALS['le']->query($str);
//    $lirun = $GLOBALS['le']->fetch_assoc();
    $aids_money = unserialize($orders['mainOrder']->UUaids_money);
    if ($aids_money){
        // 子票没有记录分润，获取子票价格
        $childMenoy = array();
        if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
            foreach($orders['childOrder'] as $key=>$child){
                $aids = explode(',',(string)$child->UUaids);
                krsort($aids);
                $aids_price = explode(',',(string)$child->UUaids_price);
                krsort($aids_price);
                foreach($aids as $k=>$et){
                    if($k==0) break;// 最后一个不用操作了
                    $childMenoy[$et]+= $aids_price[$k-1] * (string)$child->UUtnum;
                }
            }
        }
        // 主订单的 aids
        $main_aids = explode(',',(string)$orders['mainOrder']->UUaids);
//        $aids_money = unserialize($lirun['aids_money']);
        $opID = 0;
        foreach($aids_money as $row){
            $fid=$row[0];
            $action = ($row[2]==0) ? $cut : $add;//0减少,1增加和接口相反
            $Mmoney=$row[3];
            if($action==0){ // 加钱
                $ks = array_search($fid,$main_aids);
                $ks = $ks+1;
                $Mmoney += isset($childMenoy[$main_aids[$ks]]) ? $childMenoy[$main_aids[$ks]]:0;
            }else{
                $Mmoney += isset($childMenoy[$fid]) ? $childMenoy[$fid]:0;
            }

            if($row[1]==0) {//信用额度
                $dmode = 1;
                $res = $s->PFT_Member_Fund_Modify($fid,$opID,$Mmoney,$action,$dmode,$row[4],0,2,$ordern);
            } else {//资金
                $dmode = 0;
                $res = $s->PFT_Member_Fund_Modify($fid,$opID,$Mmoney,$action,$dmode,NULL,0,0,$ordern);
            }
        }
    }

    return $total_money;// 返回上级利润

}

/**
 * 获取订单总价格，以分为单位
 *
 * @param $orders array 订单数据
 * @param $daction int 是否需要原路退回0需要1不需要
 * @return int|string
 */
function total_fee($orders, $daction=0)
{
//    $total_fee = 0;
//    $aid = (int)$orders['mainOrder']->UUaid;
//    $mid = (int)$orders['mainOrder']->UUmid;

//    $id = $id_type == 'TOB' ? (int)$orders['mainOrder']->UUmid :
//        (int)$orders['mainOrder']->UUaid;

    $id = (int)$orders['mainOrder']->UUmid;
    $sql_chk_mem_type = "SELECT account,dtype FROM pft_member WHERE id=$id LIMIT 1";
    $GLOBALS['le']->query($sql_chk_mem_type);
    $GLOBALS['le']->fetch_assoc();
    $daction = 1;
    if (ismobile($GLOBALS['le']->f('account')) || $GLOBALS['le']->f('dtype')==5) {
        $daction = 0;
    }
    $total_fee = ((int)$orders['mainOrder']->UUtprice * (int)$orders['mainOrder']->UUtnum);
    $ordernum = (string)$orders['mainOrder']->UUordernum;
    $str = <<<SQL
insert pft_member_alipay set fid=$id,orderid='$ordernum',
total_fee='$total_fee',money='$total_fee',ali_account='',rectime=now(),
dtype=0,daction='$daction'
SQL;
//    insert pft_member_alipay set fid=$mid,orderid='$ordernum',
//total_fee='$total_fee',money='$total_fee',ali_account='',rectime=now(),
//dtype=0,daction=$daction
    $GLOBALS['le']->query($str);
            
    // 加上非套票的子票价格
    if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
        foreach($orders['childOrder'] as $key=>$child){
            $tmp = ((string)$child->UUtprice * (string)$child->UUtnum);
            $total_fee += $tmp;
            $ordernum = (string)$child->UUordernum;
            $str = <<<SQL
insert pft_member_alipay set fid=$id,orderid='$ordernum',total_fee='$tmp',
money='$tmp',ali_account='',rectime=now(),dtype=0,daction='$daction'
SQL;
            $GLOBALS['le']->query($str);
        }
    }
    return $total_fee;
}


// 转分销分润
function fenRun_s($s,$ordern,$aid,$mid,$total_fee,$orders,$to_pft, $discount_fee=0, $memo=''){

    $add = 0; $cut = 1;
    // 非自供产品获取结算价
    if($aid!=$mid){
        $total_money = 0;
        $pid = (string)$orders['mainOrder']->UUpid;// 产品 id
        $begintime = (string)$orders['mainOrder']->UUbegintime;// 游玩时间价格
        $account = (string)$orders['mainOrder']->UUfromt;// 游玩时间价格
        $ret = $s->Dynamic_Price_And_Storage($account,$pid,$begintime,1,0,0,$aid);
        if($ret==105||$ret==1065){
            $total_money = $total_fee;
        }else{
            $obj = simplexml_load_string($ret);
            $total_money = (string)$obj->Rec->UUsprice * (int)$orders['mainOrder']->UUtnum;
            // write_logs("UUsprice".(string)$obj->Rec->UUsprice,"debug.txt");
        }
        if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
            foreach($orders['childOrder'] as $key=>$child){
                $pid = (string)$child->UUpid;// 产品 id
                $ret = $s->Dynamic_Price_And_Storage($account,$pid,$begintime,1,0,0,$aid);
                if($ret!=105 && $ret!=1065){
                    $obj = simplexml_load_string($ret);
                    $total_money += (string)$obj->Rec->UUsprice * (int)$child->UUtnum;
                }
            }
        }
    }
    if($to_pft){// 支付给了票付通，购买者账户加钱
        //2015年7月8日15:32:19 判断是否为活动优惠倒贴钱的订单
        $self_fee = $discount_fee > 0 ? $discount_fee : $total_fee;
        write_logs("优惠活动：$mid, 0, $self_fee, $add, 0,null,0, 1,$ordern, $memo", '/var/www/html/wx/debug.txt');
        $s->PFT_Member_Fund_Modify($mid, 0, $self_fee, $add, 0,null,0, 1,$ordern, $memo);
    }

    $s->PFT_Member_Fund_Modify($aid, 0, $total_money, $add, 0,null,0, 0,$ordern, $memo);// 给上级供应商加钱
    $s->PFT_Member_Fund_Modify($mid, 0, $total_money, $cut, 0,null,0, 1,$ordern, $memo);// 购买者账户扣钱

    // 产品多级销售分润
    $str="select aids_money from uu_order_fx_details where orderid='$ordern' limit 1";
    $GLOBALS['le']->query($str);
    $lirun = $GLOBALS['le']->fetch_assoc();
    if ($lirun['aids_money']){
        // 子票没有记录分润，获取子票价格
        $childMenoy = array();
        if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
            foreach($orders['childOrder'] as $key=>$child){
                $aids = explode(',',(string)$child->UUaids);
                krsort($aids);
                $aids_price = explode(',',(string)$child->UUaids_price);
                krsort($aids_price);
                foreach($aids as $k=>$et){
                    if($k==0) break;// 最后一个不用操作了
                    $childMenoy[$et]+= $aids_price[$k-1] * (string)$child->UUtnum;
                }
            }
        }
        // 主订单的 aids
        $main_aids = explode(',',(string)$orders['mainOrder']->UUaids);
        $aids_money = unserialize($lirun['aids_money']);
        $opID = 0;
        foreach($aids_money as $row){
            $fid=$row[0];
            $action = ($row[2]==0) ? $cut : $add;//0减少,1增加和接口相反
            $Mmoney=$row[3];
            if($action==0){ // 加钱
                $ks = array_search($fid,$main_aids);
                $ks = $ks+1;
                $Mmoney += isset($childMenoy[$main_aids[$ks]]) ? $childMenoy[$main_aids[$ks]]:0;
            }else{
                $Mmoney += isset($childMenoy[$fid]) ? $childMenoy[$fid]:0;
            }

            if($row[1]==0){//信用额度
                $dmode = 1;
                $res = $s->PFT_Member_Fund_Modify($fid,$opID,$Mmoney,$action,$dmode,$row[4],0,2,$ordern, $memo);
            }else{//资金
                $dmode = 0;
                $res = $s->PFT_Member_Fund_Modify($fid,$opID,$Mmoney,$action,$dmode,NULL,0,0,$ordern, $memo);
            }
        }
    }

    return $total_money;// 返回上级利润
}

// 获取订单总价格，以分为单位
function total_fee_s($orders){
    $total_fee = 0;
    $aid = (int)$orders['mainOrder']->UUaid;
    $total_fee=((int)$orders['mainOrder']->UUtprice * (int)$orders['mainOrder']->UUtnum);
    $ordernum = (string)$orders['mainOrder']->UUordernum;
    $str="insert pft_member_alipay set fid=$aid,orderid='$ordernum',total_fee='$total_fee',money='$total_fee',ali_account='',rectime=now(),dtype=0";
    $GLOBALS['le']->query($str);

    // 加上非套票的子票价格
    if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
        foreach($orders['childOrder'] as $key=>$child){
            $tmp = ((int)$child->UUtprice * (int)$child->UUtnum);
            $total_fee+=$tmp;
            $ordernum = (string)$child->UUordernum;
            $str="insert pft_member_alipay set fid=$aid,orderid='$ordernum',total_fee='$tmp',money='$tmp',ali_account='',rectime=now(),dtype=0";
            $GLOBALS['le']->query($str);
        }
    }
    return $total_fee;
}
function write_logs($txt,$file='/var/www/html/alipay/new_log.txt'){
    $fp = fopen($file,"a");
    flock($fp, LOCK_EX);
    fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}
